package com.lastproject.web.bean;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.apache.poi.util.IOUtils;
import org.primefaces.event.FileUploadEvent;

import com.lastproject.dto.ReviewContentDTO;
import com.lastproject.ejb.dao.ReviewContentDAORemote;

@ManagedBean
@RequestScoped
public class ReviewBean {

	public static final String INVALID_FILE_EXTENSION = "The selected file must have the \"*.pdf\" extension. Please try again.";
	private String errorMessage;

	@EJB
	private ReviewContentDAORemote reviewContentDAO;

	@EJB
	ReviewContentDAORemote rcDAORemote;

	public ReviewBean() {
		super();
	}

	public ReviewBean(String filePath, String errMessage) {
		super();
		errorMessage = errMessage;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	/**
	 * Saves the PDF file on the server and writes the its location to the DB.
	 * 
	 * @param event
	 *            the file upload event
	 * @throws ParseException
	 *             in case an exception is thrown
	 */
	public void handleFileUpload(FileUploadEvent event) throws ParseException {
		InputStream is;
		// get the content of the review
		byte[] content = null;
		try {
			is = event.getFile().getInputstream();
			content = IOUtils.toByteArray(is);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// get the ID of the book
		int id = (int) event.getComponent().getAttributes().get("bookId");

		ReviewContentDTO rcDTO = new ReviewContentDTO();
		rcDTO.setContent(content);
		rcDTO.setBookId(id);

		reviewContentDAO.createContent(rcDTO);
	}
}
